import Vue from 'vue';
import { Message } from 'element-ui';
import Clipboard from 'clipboard';

function copyboard() {
	const clipboard = new Clipboard('._copy-btn');

	clipboard.on('success', e => {
		Message.success('复制成功');
		e.clearSelection();
	});

	clipboard.on('error', err => {
		console.error(err);
		Message.success('复制失败');
	});
}

copyboard();

Vue.directive('copy', {
	inserted: (el, binding) => {
		el.className = el.className + ' _copy-btn';
		el.setAttribute('data-clipboard-text', binding.value);
	},
	update: (el, binding) => {
		el.setAttribute('data-clipboard-text', binding.value);
	}
});

function addNum(el, oldNum, timerNum) {
	let timer = setInterval(() => {
		el.innerText = parseInt(parseInt(el.innerText) + parseInt(oldNum / 130));
		if (
			parseInt(el.innerText) >=
			parseInt(oldNum * 0.5 && parseInt(el.innerText) <= parseInt(oldNum * 0.6))
		) {
			clearInterval(timer);
			addNum(el, oldNum, 10);
		}
		if (
			parseInt(el.innerText) >= parseInt(oldNum * 0.6) &&
			parseInt(el.innerText) <= parseInt(oldNum * 0.7)
		) {
			clearInterval(timer);
			addNum(el, oldNum, 20);
		}
		if (
			parseInt(el.innerText) >= parseInt(oldNum * 0.7) &&
			parseInt(el.innerText) <= parseInt(oldNum * 0.8)
		) {
			clearInterval(timer);
			addNum(el, oldNum, 30);
		}
		if (
			parseInt(el.innerText) >= parseInt(oldNum * 0.8) &&
			parseInt(el.innerText) <= parseInt(oldNum * 0.9)
		) {
			clearInterval(timer);
			addNum(el, oldNum, 40);
		}
		if (
			parseInt(el.innerText) >= parseInt(oldNum * 0.9) &&
			parseInt(el.innerText) <= parseInt(oldNum * 0.95)
		) {
			clearInterval(timer);
			addNum(el, oldNum, 50);
		}
		if (
			parseInt(el.innerText) >= parseInt(oldNum * 0.95) &&
			parseInt(el.innerText) <= parseInt(oldNum * 0.99)
		) {
			clearInterval(timer);
			addNum(el, oldNum, 60);
		}
		if (parseInt(el.innerText) >= parseInt(oldNum)) {
			el.className = el.className + ' num_ani_end';
			el.innerText = oldNum;
			clearInterval(timer);
		}
	}, timerNum);
}

Vue.directive('num-ani', {
	bind: el => {
		let oldNum = el.innerText;
		el.innerText = 0;
		let timerNum = 5;
		el.className = el.className + ' num_ani';
		return (function(el) {
			addNum(el, oldNum, timerNum);
		})(el);
	},
	update: el => {
		let oldNum = el.innerText;
		el.innerText = 0;
		let timerNum = 5;
		el.className = el.className + ' num_ani';
		return (function(el) {
			addNum(el, oldNum, timerNum);
		})(el);
	}
});
